﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Testmatrix.Console
{
    class DBHelper
    {
        //DataBase connection strings
        //public static readonly string connectionString = ConfigurationManager.ConnectionStrings["url"].ConnectionString;

        //DataBase connection strings
        //public static readonly string connectionString = "Data Source=vweayvcs9j.database.windows.net,1433;Initial Catalog=testMetrics_db;"
        //                                       + "Integrated Security=SSPI";

        public static readonly string TargetConnectionString = "Data Source = fqvjleg0fd.database.windows.net,1433;Initial Catalog = test20131025_db;User Id = test20131025_db;Password = ZAQ!xsw2";

        public static readonly string SourceConnectionString = "Data Source=EDVXMQASQLCT02;Initial Catalog=MSCISDashboard;"
                                               + "Integrated Security=SSPI";
       

        public static string fileLog = @"d:\TestMetricsConsole.log";

        //Hashtable to store cached(高速缓冲存储器) parameters
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// add parameter to the cache
        /// </summary>
        /// <param name="cacheKey">Key to the parameter cache</param>
        /// <param name="cmdParms">an array of SqlParameters to be cached </param>
        public static void CacheParameters(string cacheKey, params SqlParameter[] cmdParms)
        {
            parmCache[cacheKey] = cmdParms;
        }

        #region 初始化参数值
        /// <summary>
        /// 初始化参数值
        /// </summary>
        /// <param name="paramName">存储过程名称或命令文本</param>
        /// <param name="dbType">参数类型</param>
        /// <param name="size">参数大小</param>
        /// <param name="direction">参数方向</param>
        /// <param name="value">参数值</param>
        /// <returns>新的SqlParameter对象</returns>
        private static SqlParameter MakeParam(string paramName, SqlDbType dbType, Int32 size, ParameterDirection direction, object value)
        {
            SqlParameter param;
            if (size > 0)
                param = new SqlParameter(paramName, dbType, size);
            else
                param = new SqlParameter(paramName, dbType);
            param.Direction = direction;
            if (!(direction == ParameterDirection.Output && value == null))
                param.Value = value;

            return param;
        }
        #endregion

        #region 封装成SqlParameter类型
        /// <summary>
        /// 封装成SqlParameter类型
        /// </summary>
        /// <param name="paramName">参数名/param>
        /// <param name="dbType">参数类型</param>
        /// <param name="size">参数大小</param>
        /// <param name="direction">参数方向</param>
        /// <param name="value">参数值</param>
        /// <returns>新的SqlParameter对象</returns>
        public static SqlParameter MakeInParam(string paramName, SqlDbType dbType, Int32 size, object value)
        {
            return MakeParam(paramName, dbType, size, ParameterDirection.Input, value);
        }

        #endregion


        /// <summary>
        /// Retrieve(重新得到) cashed parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParameters array</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey)
        {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
            if (cachedParms == null)
                return null;
            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
            return clonedParms;
        }

        #region Prepare a command for execution   准备一个命令去执行
        /// <summary>
        /// Prepare a command for execution   准备一个命令去执行
        /// </summary>
        /// <param name="cmd">SqlCommand object</param>
        /// <param name="conn">SqlConnection object</param>
        /// <param name="trans">SqlTransaction object</param>
        /// <param name="cmdType">Cmd Type e.g. stored procedure or text</param>
        /// <param name="cmdText">Command text,e.g. select * from Products</param>
        /// <param name="cmdParms">SqlParameter to use int the command</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            cmd.CommandTimeout = 30;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = cmdType;
            if (cmdParms != null)
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
        }
        #endregion



        #region 执行命令文本，并返回SqlDataReader(连接式的)

        /// <summary>
        /// Execute a SqlCommand that returns a resultSet against the database specified in the connection string
        /// using the provided parameters
        /// <remarks>
        /// e.g.
        /// SqlDataReader reader=ExecuteReader(connStrng,CommandType.StoreProcedure,"PublishOrders",new SqlParameter("@prodid",24))
        /// </remarks>
        /// </summary>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="cmdType">the CommandType</param>
        /// <param name="cmdText">the stored procedure name or T-SQL command</param>
        /// <param name="cmdParms">an array of Parameters used to execute the command</param>
        /// <returns>a SqlDataReader containg the results</returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
            //we use a try/catch here because if the method throws an exception we want to
            //close the connection throw code,because no datareader will exist,hence(因此)the
            //CommandBehavior.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return reader;
            }
            catch (Exception ex)
            {
                conn.Close();
                IOHelper.Log("ExecuteReader ==========>  " + ex.ToString(), fileLog);
                return null;
            }
        }
        #endregion

        #region 执行命令文本(传入连接字符串)，返回受影响的行数
        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
        /// using the provided parameters
        /// </summary>
        /// <remarks>
        /// e.g.
        /// int result=ExecuteNonQuery(connString,CommandType.StoredProcedure,"PublishOrders",new SqlParameter("@prodid",24))
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="cmdType">the CommandType</param>
        /// <param name="cmdText">the Stored procedure name or T-SQL command</param>
        /// <param name="cmdPrams">an array of SqlParameters used to execute the command</param>
        /// <returns>an int representing the number or rows affected by the command</returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] cmdPrams)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                try
                {
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdPrams);
                    int val = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    return val;
                }
                catch (Exception ex)
                {
                    IOHelper.Log("ExecuteNonQuery ==========>  " + ex.ToString(), fileLog);
                    return -1;
                }
            }
        }
        #endregion

        #region 执行命令文本(传入已经存在的连接对象)，返回受影响的行数
        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against an existing database connection
        /// using the provided parameters
        /// </summary>
        /// <remarks>
        /// e.g.
        /// int result=ExecuteNonQuery(conn,CommandType.StoredProcedure,"PublishOrders",new SqlParameter("@prodid",24))
        /// </remarks>
        /// <param name="connectionString">an existint database connection</param>
        /// <param name="cmdType">the CommandType</param>
        /// <param name="cmdText">the Stored procedure name or T-SQL command</param>
        /// <param name="cmdPrams">an array of SqlParameters used to execute the command</param>
        /// <returns>an int representing the number or rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] cmdPrams)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, null, cmdType, cmdText, cmdPrams);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;

        }
        #endregion

        #region 执行命令文本(传入已经存在的连接对象)，返回受影响的行数
        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) using an existing SqlTransaction
        /// using the provided parameters
        /// </summary>
        /// <remarks>
        /// e.g.
        /// int result=ExecuteNonQuery(sqlTrans,CommandType.StoredProcedure,"PublishOrders",new SqlParameter("@prodid",24))
        /// </remarks>
        /// <param name="connectionString">an existint sql transaction</param>
        /// <param name="cmdType">the CommandType</param>
        /// <param name="cmdText">the Stored procedure name or T-SQL command</param>
        /// <param name="cmdPrams">an array of SqlParameters used to execute the command</param>
        /// <returns>an int representing the number or rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] cmdPrams)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdPrams);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }
        #endregion



        #region 执行命令文本(传入连接字符串)，返回单个对象
        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
        /// using the provided parameters
        /// </summary>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="cmdType">the CommandType</param>
        /// <param name="cmdText">the storedd procedure name or T-SQL command</param>
        /// <param name="cmdParms">an array of SqlParameters used to execute the command</param>
        /// <returns>An object that should be converted to the expected(期望) type using Convert.To{Type}</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                try
                {
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                    object val = cmd.ExecuteScalar();
                    cmd.Parameters.Clear();
                    return val;
                }
                catch (Exception ex)
                {
                    IOHelper.Log("ExecuteScalar ==========>  " + ex.ToString(), fileLog);
                    return null;
                }

            }
        }
        #endregion

        #region 执行命令文本(传入连接对象)，返回单个对象
        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against an existing database connection
        /// using the provided parameters
        /// </summary>
        /// <param name="connectionString">an existing database connection</param>
        /// <param name="cmdType">the CommandType</param>
        /// <param name="cmdText">the storedd procedure name or T-SQL command</param>
        /// <param name="cmdParms">an array of SqlParameters used to execute the command</param>
        /// <returns>An object that should be converted to the expected(期望) type using Convert.To{Type}</returns>
        public static object ExecuteScalar(SqlConnection conn, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
        {
            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }
        #endregion

        #region 执行命令文本(传入连接对象)，返回单个对象
        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against an existing database connection
        /// using the provided parameters
        /// </summary>
        /// <param name="connectionString">an existing database connection</param>
        /// <param name="cmdType">the CommandType</param>
        /// <param name="cmdText">the storedd procedure name or T-SQL command</param>
        /// <param name="cmdParms">an array of SqlParameters used to execute the command</param>
        /// <returns>An object that should be converted to the expected(期望) type using Convert.To{Type}</returns>
        public static object ExecuteScalar(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }
        #endregion
    }
}
